<?php

namespace app\job\event;

use app\api\model\plus\invitationgift\InvitationReward as InvitationRewardModel;
use app\api\model\plus\invitationgift\InvitationReceive as InvitationReceiveModel;
use app\api\model\plus\invitationgift\Partake as PartakeModel;
use app\api\model\plus\invitationgift\InvitationGift as InvitationGiftModel;
use app\job\model\user\User as UserModel;
use app\job\model\order\Order as OrderModel;
use app\api\model\plus\coupon\UserCoupon;
use app\common\model\user\BalanceLog as BalanceLogModel;
use app\common\enum\user\balanceLog\BalanceLogSceneEnum;

/**
 * 邀请好友管理
 */
class Invitation
{
    private $user_id;
    private $invitation_gift_id;
    private $inv_type;

    /**
     * 执行函数 type:0邀请成为会员1邀请成为好友且消费2被邀请人会员奖励3被邀请人消费奖励
     */
    public function handle($data)
    {
        $this->user_id = $data['user_id'];
        $this->invitation_gift_id = $data['invitation_gift_id'];
        $this->inv_type = $data['inv_type'];
        if ($data['type'] == 0) {
            $this->inviteStatus();
        } else if ($data['type'] == 1) {
            $this->inviteOrderStatus();
        } else if ($data['type'] == 2 || $data['type'] == 3) {
            if ($data['type'] == 2) {
                $type = 1;
            } else {
                $type = 2;
            }
            $this->inceptGift($type);
        }
        return true;
    }

    //判断邀请好友数量
    public function inviteStatus()
    {
        $PartakeModel = new PartakeModel();
        //邀请总人数
        $count = $PartakeModel->where('invitation_gift_id', '=', $this->invitation_gift_id)
            ->where('user_id', '=', $this->user_id)
            ->count();
        $data['count'] = $count;
        $this->receiveGift($data);

    }

    //判断邀请好友且消费
    public function inviteOrderStatus()
    {
        $PartakeModel = new PartakeModel();
        //邀请总人数
        $partake_id = $PartakeModel->where('invitation_gift_id', '=', $this->invitation_gift_id)
            ->where('user_id', '=', $this->user_id)
            ->column('partake_id');
        $count = (new OrderModel())->where('user_id', 'in', $partake_id)
            ->where('pay_status', '=', 20)
            ->group('user_id')
            ->count();
        $data['count'] = $count;
        $this->receiveGift($data);

    }

    //判断是否满足条件赠送礼品
    private function receiveGift($data)
    {
        $count = $data['count'];
        //奖品
        $InvitationRewardModel = new InvitationRewardModel();
        $gift = [];
        $receive = [];
        if ($this->inv_type == 0) {//阶梯奖励
            $reward = $InvitationRewardModel->where('reward_type', '=', 0)
                ->where('invitation_gift_id', '=', $this->invitation_gift_id)
                ->order('invitation_num desc')
                ->select();
            foreach ($reward as $key => $value) {
                if ($count >= $value['invitation_num']) {
                    $gift = $value;
                    break;
                }
            }
            //判断有没有送
            $receive = (new InvitationReceiveModel())->where('user_id', '=', $this->user_id)
                ->where('invitation_gift_id', '=', $this->invitation_gift_id)
                ->where('invitation_reward_id', '=', $gift['invitation_reward_id'])
                ->find();
        } elseif ($this->inv_type == 1) {//单次奖励
            $gift = $InvitationRewardModel->where('reward_type', '=', 0)
                ->where('invitation_gift_id', '=', $this->invitation_gift_id)
                ->find();
            if (!$gift || $count < $gift['invitation_num']) {
                return false;
            }
            //判断有没有送
            $receive = (new InvitationReceiveModel())->where('user_id', '=', $this->user_id)
                ->where('invitation_gift_id', '=', $this->invitation_gift_id)
                ->find();
        } elseif ($this->inv_type == 2) {//循环奖励
            $gift = $InvitationRewardModel->where('reward_type', '=', 0)
                ->where('invitation_gift_id', '=', $this->invitation_gift_id)
                ->find();
            if (!$gift || $count < $gift['invitation_num'] || $gift['invitation_num'] <= 0) {
                return false;
            }
            $ratio = $count / $gift['invitation_num'];
            if ($ratio < 1) {
                return false;
            }
            $ratio = floor($ratio) * $gift['invitation_num'];
            //判断有没有送
            $receive = (new InvitationReceiveModel())->where('user_id', '=', $this->user_id)
                ->where('invitation_gift_id', '=', $this->invitation_gift_id)
                ->where('invitation_num', '=', $ratio)
                ->where('reward_type', '=', 0)
                ->order('invitation_receive_id desc')
                ->find();
        }
        //满足条件送礼品
        if ($gift && !$receive) {
            $addGift = [
                'invitation_num' => $count,
                'user_id' => $this->user_id,
                'invitation_gift_id' => $this->invitation_gift_id,
                'invitation_reward_id' => $gift['invitation_reward_id'],
                'point' => $gift['is_point'] == 1 ? $gift['point'] : 0,
                'coupon' => $gift['is_coupon'] == 1 ? json_encode($gift['coupon']) : '',
                'balance' => $gift['is_balance'] == 1 ? $gift['balance'] : 0,
                'app_id' => $gift['app_id']
            ];
            //增加记录
            (new InvitationReceiveModel())->save($addGift);
            // 用户模型
            $user = UserModel::detail($this->user_id);
            // 修改用户积分
            if ($addGift['point'] > 0) {
                $user->setIncPoints($addGift['point'], '邀请有礼奖励');
            }
            if ($addGift['balance'] > 0) {
                $user->save(['balance' => $user['balance'] + $addGift['balance']]);
                BalanceLogModel::add(BalanceLogSceneEnum::AWARD, [
                    'user_id' => $user['user_id'],
                    'money' => $addGift['balance'],
                    'app_id' => $user['app_id'],
                ], ['order_no' => '邀请有礼奖励' . '，活动ID：' . $addGift['invitation_gift_id']]);
            }
            //添加优惠券
            if ($addGift['coupon']) {
                $UserCouponModel = new UserCoupon;
                $UserCouponModel->addNewUserCoupon($addGift['coupon'], $user['user_id'], $user['app_id']);
            }

        }
        return true;
    }

    //被邀请人成为会员奖励和被邀请人消费奖励
    public function inceptGift($type)
    {
        $InvitationRewardModel = new InvitationRewardModel();
        $reward = $InvitationRewardModel->where('reward_type', '=', $type)
            ->where('invitation_gift_id', '=', $this->invitation_gift_id)
            ->find();
        $gift = [
            'user_id' => $this->user_id,
            'invitation_gift_id' => $this->invitation_gift_id,
            'invitation_reward_id' => $reward['invitation_reward_id'],
            'point' => $reward['is_point'] == 1 ? $reward['point'] : 0,
            'coupon' => $reward['is_coupon'] == 1 ? json_encode($reward['coupon']) : '',
            'balance' => $reward['is_balance'] == 1 ? $reward['balance'] : 0,
            'reward_type' => $type,
            'app_id' => $reward['app_id']
        ];
        //增加记录
        (new InvitationReceiveModel())->save($gift);
        // 用户模型
        $user = UserModel::detail($this->user_id);
        $describe = $type == 1 ? "邀请有礼成为会员奖励" : "邀请有礼成为会员消费奖励";
        // 修改用户积分
        if ($gift['point'] > 0) {
            $user->setIncPoints($gift['point'], $describe);
        }
        if ($gift['balance'] > 0) {
            $user->save(['balance' => $user['balance'] + $gift['balance']]);
            BalanceLogModel::add(BalanceLogSceneEnum::AWARD, [
                'user_id' => $user['user_id'],
                'money' => $gift['balance'],
                'app_id' => $user['app_id'],
            ], ['order_no' => $describe . '，活动ID:' . $gift['invitation_gift_id']]);
        }
        //添加优惠券
        if ($gift['coupon']) {
            $UserCouponModel = new UserCoupon;
            $UserCouponModel->addNewUserCoupon($gift['coupon'], $user['user_id'], $user['app_id']);
        }
    }
}
